package com.zjun.demo.experimentaldemo.audio

import android.annotation.SuppressLint
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioDeviceInfo
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Build
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import com.zjun.demo.experimentaldemo.R
import com.zjun.demo.experimentaldemo.base.BaseActivity
import com.zjun.demo.experimentaldemo.databinding.ActivityDynamicAddBinding


/**
 * 监听是否有新的音频设备接入，如果新的音频设备,则使用他,动态切换音频来源,应用于有视频通话或者语音通话过程中有新的音频设备接入时可以动态更换
 * 蓝牙耳机的监听需要申请<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
 */
class AudioActivity : BaseActivity<ActivityDynamicAddBinding>() {

    private val tag = "AudioActivity"

    private var mAudioManagerMode = -1

    private var mAudioIsMicrophoneMute: Boolean? = null

    private var mAudioDeviceInfo: AudioDeviceInfo? = null

    private var mIsSpeakerphoneOn: Boolean? = null

    private var mHeadsetStateProvider: HeadsetStateProvider? = null

    private var mBluetoothHeadsetStateProvider: BluetoothHeadsetStateProvider? = null

    lateinit var audioManager:AudioManager

    /**
     * 播放门铃的MediaPlayer
     */
    private var mMediaPlayer: MediaPlayer? = null

    override fun getLayoutId(): Int = R.layout.activity_audio

    override fun initialize() {
         audioManager = ContextCompat.getSystemService(this, AudioManager::class.java) ?: return
//        startRing(true)
//        getDefaultAudio(this)
//        mHeadsetStateProvider = HeadsetStateProvider(this, ::headsetIsConnected)
//        mBluetoothHeadsetStateProvider = BluetoothHeadsetStateProvider(this, ::bluetoothHeadsetIsConnected)
    }

    /**
     * 播放铃音
     */
    private fun startRing(isLooping: Boolean = true) {
        try {
            if (mMediaPlayer == null) {
                mMediaPlayer = MediaPlayer.create(this, R.raw.video_request)
                mMediaPlayer?.setAudioAttributes(
                    AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                        .setUsage(AudioAttributes.USAGE_ALARM)
                        .build()
                )
            }
            //默认循环播放
            mMediaPlayer?.isLooping = isLooping
            mMediaPlayer?.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 停止播放铃音
     */
    private fun stopRing() {
        try {
            if (null != mMediaPlayer) {
                mMediaPlayer?.stop()
                mMediaPlayer = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /**
     * 有线耳机
     */
    private fun headsetIsConnected(headsetIsConnected: Boolean) {
        Log.i(tag, "有线耳机 = $headsetIsConnected")
        turnSpeakerphone(headsetIsConnected)
    }

    /**
     * 无线耳机
     */
    private fun bluetoothHeadsetIsConnected(headsetIsConnected: Boolean) {
        Log.i(tag, "无线耳机 = $headsetIsConnected")
        turnSpeakerphone(headsetIsConnected)
    }


    /**
     * 关闭或者开启扬声器
     */
    @Suppress("DEPRECATION")
    private fun turnSpeakerphone(originalSpeakerphoneOn: Boolean, audioPriority: IntArray? = null) {
        runOnUiThread {
            //按设备类型设置优先级
            val newAudioPriority = audioPriority ?: intArrayOf(
                AudioDeviceInfo.TYPE_WIRED_HEADSET,
                AudioDeviceInfo.TYPE_WIRED_HEADPHONES,
                AudioDeviceInfo.TYPE_BLUETOOTH_SCO,
                AudioDeviceInfo.TYPE_BUILTIN_SPEAKER
            )
//        val audioManager = ContextCompat.getSystemService(this, AudioManager::class.java)
            if (audioManager != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    val devices: List<AudioDeviceInfo> = audioManager.availableCommunicationDevices
                    var speakerDevice: AudioDeviceInfo? = null
                    Log.i(tag, "无线耳机,设备数量 = ${devices.size}")
                    loop@ for (audioType in newAudioPriority) {
                        for (device in devices) {
                            if (device.type == audioType) {
                                Log.i(tag, "无线耳机 = audioType = $audioType")
                                speakerDevice = device
                                break@loop
                            }
                        }
                    }
                    if (speakerDevice != null) {
                        if (originalSpeakerphoneOn) {
                            val result = audioManager.setCommunicationDevice(speakerDevice)
                            Log.i(tag, "setCommunicationDevice result = $result")
                        }
                    }
                } else {
                    if (!audioManager.isBluetoothScoOn) {
                        audioManager.startBluetoothSco()
                        audioManager.isBluetoothScoOn = originalSpeakerphoneOn
                    } else {
                        audioManager.isSpeakerphoneOn = originalSpeakerphoneOn
                    }
                }
            }
        }

    }


    /**
     * 通话结束后，音频焦点对我们不再有用，恢复一开始保存的设置
     */
    @SuppressLint("WrongConstant")
    @Suppress("DEPRECATION")
    private fun resetAudio(context: Context) {
//        val audioManager = ContextCompat.getSystemService(context, AudioManager::class.java) ?: return
        if (mAudioManagerMode != -1) {
            audioManager.mode = mAudioManagerMode
            audioManager.isMicrophoneMute = mAudioIsMicrophoneMute!!
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                audioManager.setCommunicationDevice(mAudioDeviceInfo!!)
            } else {
                audioManager.isSpeakerphoneOn = mIsSpeakerphoneOn!!
            }
        }
    }

    /**
     * 进入这个页面时临时保存进入的状态
     */
    @Suppress("DEPRECATION")
    private fun getDefaultAudio(context: Context) {
//        val audioManager = ContextCompat.getSystemService(context, AudioManager::class.java) ?: return
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            mAudioDeviceInfo = audioManager.communicationDevice
        } else {
            mIsSpeakerphoneOn = audioManager.isSpeakerphoneOn
        }
        mAudioManagerMode = audioManager.mode
        mAudioIsMicrophoneMute = audioManager.isMicrophoneMute
    }

    override fun onDestroy() {
        //还原进入这个页面之前的音频状态
        resetAudio(this)
        //防止内存泄漏
        mHeadsetStateProvider?.unregisterReceiver()
        mBluetoothHeadsetStateProvider?.release()
        stopRing()
        super.onDestroy()
    }

    fun logDevices(view: View) {
//        val audioManager = ContextCompat.getSystemService(this, AudioManager::class.java) ?: return
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val devices: List<AudioDeviceInfo> = audioManager.availableCommunicationDevices
            for (device in devices){
                Log.i(tag, "logDevices = ${device.type}")
            }
        }
    }

    fun volumeLog(view: View) {
        val streamVoiceCallVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL)
        val streamSystemVolume = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM)
        val streamRingVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING)
        val streamMusicVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        val streamAlarmVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM)
        val streamNotificationVolume = audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION)
        val streamDtmVolume = audioManager.getStreamVolume(AudioManager.STREAM_DTMF)
        Log.i(tag, "streamVoiceCallVolume = $streamVoiceCallVolume,streamSystemVolume = $streamSystemVolume,streamRingVolume = $streamRingVolume,streamMusicVolume = $streamMusicVolume,streamAlarmVolume = $streamAlarmVolume,,streamNotificationVolume = $streamNotificationVolume,streamDtmVolume = $streamDtmVolume")
    }


}